<template>
  <div class="mb-3">
    <el-echarts
      theme="macarons"
      :height="300"
      :width="width"
      @onInit="onInit"
      v-show="!imgType"
      :option="option"
    ></el-echarts>
    <img height="300" class="w-100" v-show="imgType" :src="imgData" alt="" />
  </div>
</template>
<script>
export default {
  components: {},
  props: {
    categoryCode: String,
    customerRelatedId: String,
    imgType: Boolean,
    width: {
      type: [Number, String],
      default: '100%',
    },
  },
  data() {
    return {
      chart: null,
      option: null,
      imgData: '',
    }
  },
  computed: {},
  watch: {
    customerRelatedId() {
      this.getData()
    },
    categoryCode() {
      this.getData()
    },
  },
  created() {
    this.getData()
  },
  mounted() {},
  methods: {
    onInit(chart) {
      this.chart = chart
    },
    async getData() {
      if (!this.customerRelatedId) {
        return
      }

      this.$http
        .get('/industrial/customer/category/funds/', {
          params: {
            categoryCode: this.categoryCode,
            customerRelatedId: this.customerRelatedId,
          },
        })
        .then(res => {
          if (res && res.data) {
            const data = res.data
            this.setOption({
              title: '',
              subtext: '',
              legend: ['金额'],
              xData: ['最大值', '平均值', '最小值', '申请值'],
              seriesData: [
                {
                  name: '金额',
                  type: 'bar',
                  barMaxWidth: 40,
                  data: [
                    data.maxFunds || 0,
                    data.avgFunds || 0,
                    data.minFunds || 0,
                    data.myFunds || 0,
                  ],
                  markLine: {
                    data: [{ yAxis: data.avgFunds || 0, name: '平均值' }],
                  },
                },
              ],
            })
          } else {
            this.setOption({})
          }
        })
        .catch(() => {
          this.setOption({})
        })
    },

    setOption(data) {
      this.option = {
        backgroundColor: '#eff8fe',
        title: {
          text: data.title || '',
          subtext: data.subtext || '',
          left: 'center',
        },
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          top: 32,
          data: data.legend || [],
        },
        xAxis: [
          {
            type: 'category',
            data: data.xData || [],
          },
        ],
        yAxis: [
          {
            type: 'value',
            name: '金额',
          },
        ],
        series: data.seriesData || [],
      }
      if (this.customerRelatedId && this.chart && this.chart.getDataURL) {
        this.chart.on('finished', () => {
          this.imgData = this.chart.getDataURL()
        })
      }
    },
  },
}
</script>
<style scoped></style>
